
#include "my_net.h"
#include <netdb.h>
#include <stdio.h>
#include <strings.h>
#include <netinet/in.h>
#include <sys/socket.h>

sockfd TcpListen(const char *host, const char *serivce, socklen_t *result_addr_len) {

    struct addrinfo hints;
    struct addrinfo * result = NULL;
    bzero(&hints, sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_family   = AF_UNSPEC;
    hints.ai_flags    = AI_PASSIVE;

    int result_int = getaddrinfo(host, serivce, &hints, &result);

    sockfd fd = -1;
    if (result_int == 0){

        struct addrinfo * ptr = result;
        fd = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
        // bind all address 
        while (ptr) {

            PrintSockaddr(ptr->ai_addr, ptr->ai_addrlen);
            if (bind(fd, ptr->ai_addr, ptr->ai_addrlen) == -1){

                ptr = ptr->ai_next;
                continue;
            }
            ptr = ptr->ai_next;
        }
    }
    listen(fd, 10000);
    printf("getaddrinfo result : %d and sockfd = %d\n", result_int,fd);
    freeaddrinfo(result);
    return fd;
}
